package com.hanson.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanson.Const;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.bean.SearchBean;
import com.hanson.common.bean.WeiXinConfig;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.util.BusinessUtil;
import com.hanson.common.util.FileUploadUtil;
import com.hanson.entity.ScoreSeqBean;
import com.hanson.entity.SpreadInfoBean;
import com.hanson.entity.SpreadMoneyBean;
import com.hanson.entity.UserBean;
import com.hanson.mapper.SpreadMoneyBeanMapper;
import com.hanson.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Api(tags = "用户数据管理")
@RestController
@RequestMapping("/api/user")
public class UserApiController {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private SpreadInfoService spreadInfoService;
    @Value("${oss.local}")
    private String isLocal;
    @Autowired
    private AcctbkService acctbkService;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private CouponsService couponsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SpreadMoneyBeanMapper spreadMoneyBeanMapper;

    @ApiOperation(value = "分页获取积分兑换商品")
    @RequestMapping(value = "/getScoreGoods/{page}/{limit}", method = RequestMethod.GET)
    public ResultMessage getBestGoods(@PathVariable Integer page, @PathVariable Integer limit) throws Exception {
        ModelMap modelMap = new ModelMap();
        SearchBean scoreBean = new SearchBean();
        scoreBean.setIsScore(1);
        return ResultMessage.success(goodsService.getSimpleGoodsList(page, limit, scoreBean, modelMap), null);
    }


    @ApiOperation(value = "获取我的优惠卷", notes = "type: 1可用 2过期或已使用")
    @RequestMapping(value = "/getUserCoupons/{type}", method = RequestMethod.GET)
    public ResultMessage getUserCoupons(HttpServletRequest request, @PathVariable Integer type) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        return ResultMessage.success(couponsService.getUserCoupons(openId, type), null);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @RequestMapping(value = "/getCurrentUser", method = RequestMethod.GET)
    public ResultMessage getCurrentUser(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        UserBean userBean = userService.selectByOpenId(openId);
        if (null != userBean) {
            List<SpreadMoneyBean> receivingList = spreadMoneyBeanMapper.selectByOpenId(userBean.getOpenId(), 0);
            List<SpreadMoneyBean> receivedList = spreadMoneyBeanMapper.selectByOpenId(userBean.getOpenId(), 1);
            if (CollectionUtils.isNotEmpty(receivingList)) {
                userBean.setSpreadMoneyReceiving(BusinessUtil.getWebAmount(receivingList.stream().mapToInt(SpreadMoneyBean::getSpreadMoney).sum()));
            }
            if (CollectionUtils.isNotEmpty(receivedList)) {
                userBean.setSpreadMoneyReceived(BusinessUtil.getWebAmount(receivedList.stream().mapToInt(SpreadMoneyBean::getSpreadMoney).sum()));
            }
        }
        return ResultMessage.success(userBean, null);
    }

    @ApiOperation(value = "获取我的账户汇总信息")
    @RequestMapping(value = "/acctbkInfo", method = RequestMethod.GET)
    public ResultMessage acctbkInfo(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        return ResultMessage.success(acctbkService.getAcctbkInfoByOpenId(openId), null);
    }

    @ApiOperation(value = "获取我的账户流水")
    @RequestMapping(value = "/getAcctbkSeq/{page}/{limit}", method = RequestMethod.GET)
    public ResultMessage getAcctbkSeq(HttpServletRequest request, @PathVariable Integer page, @PathVariable Integer limit) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        return ResultMessage.success(acctbkService.getAcctbkInfoPageByOpenId(openId, page, limit), null);
    }

    @ApiOperation(value = "获取我的汇总积分信息")
    @RequestMapping(value = "/scoreInfo", method = RequestMethod.GET)
    public ResultMessage scoreInfo(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ModelMap modelMap = new ModelMap();
        List<ScoreSeqBean> scoreSeqBeanList = scoreService.getScoreInfoByOpenId(openId, modelMap);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", scoreSeqBeanList);
        jsonObject.put("totalScore", modelMap.get("totalScore"));
        jsonObject.put("totalGetScore", modelMap.get("totalGetScore"));
        jsonObject.put("totalPutScore", modelMap.get("totalPutScore"));
        jsonObject.put("todayScore", modelMap.get("todayScore"));
        return ResultMessage.success(jsonObject, null);
    }

    @ApiOperation(value = "获取我的积分流水")
    @RequestMapping(value = "/getScoreSeq/{page}/{limit}", method = RequestMethod.GET)
    public ResultMessage getScoreSeq(HttpServletRequest request, @PathVariable Integer page, @PathVariable Integer limit) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        List<ScoreSeqBean> scoreSeqBeanList = scoreService.getScoreInfoPageByOpenId(openId, page, limit);
        return ResultMessage.success(scoreSeqBeanList, null);
    }

    @ApiOperation(value = "获取我的二维码")
    @RequestMapping(value = "/qrCode", method = RequestMethod.GET)
    public ResultMessage qrCode(HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        UserBean userBean = userService.selectByOpenId(openId);
        if (null == userBean) {
            throw new BusinessException("当前用户不存在 请联系管理员");
        } else {
            if (userBean.getIsSpread() == 0) {
                throw new BusinessException("您目前不是合伙人 请先申请合伙人");
            } else {
                String userSign = userBean.getUserSign();
                if (StringUtils.isNotEmpty(userSign)) {
                    String[] signArray = userSign.split(",");
                    String client = BusinessUtil.getHeaderClient(request);
                    if (client.equals(Const.CLIENT_MINI)) {
                        userSign = signArray[0];
                    } else {
                        userSign = signArray[1];
                    }
                }
                return ResultMessage.success(userSign, null);
            }
        }
    }

    @ApiOperation(value = "新增粉丝")
    @RequestMapping(value = "/add/{pid}", method = RequestMethod.POST)
    public ResultMessage add(@PathVariable Integer pid, HttpServletRequest request) {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        spreadInfoService.addSpreadUniApp(openId, pid);
        resultMessage.setMsg("操作成功！");
        return resultMessage;
    }

    @ApiOperation(value = "获取我的粉丝")
    @RequestMapping(value = "/myFans/{page}/{limit}", method = RequestMethod.GET)
    public ResultMessage myFans(HttpServletRequest request, String search, @PathVariable Integer page, @PathVariable Integer limit) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        Page<SpreadInfoBean> pageInfo = new Page<>(page, limit);
        List<SpreadInfoBean> spreadInfoBeanList = spreadInfoService.selectChildsPage(openId, search, pageInfo);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data", spreadInfoBeanList);
        jsonObject.put("total", CollectionUtils.isNotEmpty(spreadInfoBeanList) ? spreadInfoBeanList.size() : 0);
        UserBean userBean = userService.selectByOpenId(openId);
        return ResultMessage.success(jsonObject, null);
    }

    @ApiOperation(value = "查看粉丝详情")
    @RequestMapping(value = "/fansDetail/{openId}", method = RequestMethod.GET)
    public ResultMessage fansDetail(@PathVariable String openId, HttpServletRequest request) throws Exception {
        return ResultMessage.success(orderService.getFansDetail(openId, true), null);
    }

    @ApiOperation(value = "文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessage upload(HttpServletRequest request) throws Exception {
        JSONObject jsonObject = FileUploadUtil.uploadOssFile(request, isLocal);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(jsonObject.containsKey("src") ? jsonObject.get("src") : "");
        return resultMessage;
    }

    @ApiOperation(value = "修改当前用户信息")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResultMessage update(@RequestBody UserBean userBean, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getHeaderOpenId(request);
        ResultMessage resultMessage = new ResultMessage();
        UserBean returnBean = userService.selectByOpenId(openId);
        if (null != returnBean) {
            userBean.setId(returnBean.getId());
            userService.updateUser(userBean);
        }
        resultMessage.setMsg("操作成功！");
        return resultMessage;
    }

}
